package com.gobang.gobangboot.controller.user;

import com.gobang.gobangboot.entity.User.User;
import com.gobang.gobangboot.entity.User.UserRegisterDTO;
import com.gobang.gobangboot.entity.User.UserVO;
import com.gobang.gobangboot.entity.common.Result;
import com.gobang.gobangboot.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("/user")
@Tag(name = "用户相关接口")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    private final String CODE_KEY = "USER:CODE:";


    @Operation(summary = "登录请求")
    @PostMapping("/login")
    public Result<String> login(@RequestBody UserRegisterDTO userDTO){
        System.out.println(userDTO.getPhone());
        String token = userService.login(userDTO);

        return Result.success(token);
    }

    @PostMapping("/register")
    public Result register(@RequestBody UserRegisterDTO userDTO){
        userService.register(userDTO);
        return Result.success();
    }

//    获取用户信息
    @GetMapping("/getInfo")
    public Result<User> getInfo(){
        User vo = userService.getInfo();
        return Result.success(vo);
    }

    @GetMapping("/getEnemy")
    public Result<UserVO> getEnemy(String enemyName){
        UserVO vo = userService.getEnemy(enemyName);
        return Result.success(vo);
    }

    @Operation(summary = "获取验证码")
    @GetMapping("/getCode")
    public Result<String> getCode(String phone){
        System.out.println(phone);
        String codeStatus = redisTemplate.opsForValue().get(CODE_KEY + phone);
        if (codeStatus != null){
            throw new RuntimeException("还没有两分钟呢牢底，别这么频繁申请啊！");
        }
        Random random = new Random();
        String code = String.valueOf(random.nextInt(900000) + 100000);
        redisTemplate.opsForValue().set(CODE_KEY + phone, code, 2, TimeUnit.MINUTES);
        return Result.success(code);
    }

    @Operation(summary = "根据验证码登录")
    @PostMapping("/loginByCode")
    public Result<String> loginByCode(@RequestBody UserRegisterDTO dto){
        String token = userService.loginByCode(dto);
        return Result.success(token);
    }



//    更新用户头像
    private static final String UPLOAD_DIR = "avatar/";
    @PostMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam("file") MultipartFile avatarFile){
        if(avatarFile.isEmpty()){
            return Result.error("文件上传失败");
        }
        try {
            // 创建上传目录
            File uploadDir = new File(UPLOAD_DIR);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }
            //文件名=当前时间到毫秒+原来的文件名
            String fileName = System.currentTimeMillis()+avatarFile.getOriginalFilename();
            // 构建上传文件路径
            Path uploadPath = Paths.get(UPLOAD_DIR + fileName);
            // 保存文件
            Files.copy(avatarFile.getInputStream(), uploadPath, StandardCopyOption.REPLACE_EXISTING);
//            数据库存的相对地址
            String urlPath = "/avatar/"+fileName;

            userService.updateAvatar(urlPath);
            User userInfo = userService.getInfo();

            return Result.success(userInfo);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error("Failed to upload file");
        }
    }

//    更新用户信息
    @PostMapping("/updateUserInfo")
    public Result updateUserInfo(@RequestBody @Validated User user){
//        System.out.println("controller-user:"+user);
        userService.updateUserInfo(user);
        User newUser = userService.getInfo();
        return Result.success(newUser);
    }

//    修改密码
    @PostMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String,String> dataMap){
        System.out.println("userRegisterDTO"+dataMap);
        String phone = dataMap.get("phone");
        String oldPwd = dataMap.get("oldPwd");
        User user = userService.getInfo();
        if(!phone.equals(user.getPhone())){
            return Result.error("手机号错误！");
        }
        if(!oldPwd.equals(user.getPassword())){
            return Result.error("原密码错误！");
        }
        String rePwd = dataMap.get("rePwd");
        User userForRePwd = new User();
        userForRePwd.setPassword(rePwd);
        userService.updateUserInfo(userForRePwd);
        return Result.success("修改成功");
    }
}
